﻿using System;
using System.ComponentModel;

namespace Library.OrmEnterpriseEntity.TableInfo {
	internal class ColumnPropertyDescriptor : PropertyDescriptor {
		internal static readonly TypeConverter ByteConverter = new ByteConverter();
		internal static readonly TypeConverter Int16Converter = new Int16Converter();
		internal static readonly TypeConverter Int32Converter = new Int32Converter();
		internal static readonly TypeConverter Int64Converter = new Int64Converter();
		internal static readonly TypeConverter DateConverter = new DateTimeConverter();
		internal static readonly TypeConverter BooleanConverter = new BooleanConverter();
		internal static readonly TypeConverter StringConverter = new StringConverter();
		internal static readonly TypeConverter DoubleConverter = new DoubleConverter();
		internal static readonly TypeConverter DecimalConverter = new DecimalConverter();
		internal static readonly TypeConverter SingleConverter = new SingleConverter();



		private readonly Type _componentType;
		private readonly Type _propertyType;
		private readonly TypeConverter _typeConverter;

		public ColumnPropertyDescriptor(MemberDescriptor descr, Type componentType, Type propertyType, TypeConverter typeConverter)
			: base(descr) {
			_componentType = componentType;
			_propertyType = propertyType;
			_typeConverter = typeConverter;
		}


		public override bool CanResetValue(object component) {
			return true;
		}

		private int _columnIndex = -1;
		public override object GetValue(object component) {
			var entity = (DbTable)component;
			DbColumn col = FindColumn(entity);
			return col.DbValue;
		}

		private DbColumn FindColumn(DbTable entity) {
			DbColumn col;
			if (_columnIndex == -1) {
				col = entity.Columns.Find(Name);
				_columnIndex = col.ColumnIndex;
			} else {
				col = entity.Columns.Find(_columnIndex);
			}
			return col;
		}

		public override void ResetValue(object component) {
			var entity = (DbTable)component;
			entity.Columns.RestoreFromDb();
		}

		public override void SetValue(object component, object value) {
			var entity = (DbTable)component;
			DbColumn col = FindColumn(entity);
			col.DbValue = value;
		}

		public override bool ShouldSerializeValue(object component) {
			return false;
		}

		public override Type ComponentType {
			get { return _componentType; }
		}

		public override bool IsReadOnly {
			get { return false; }
		}

		public override Type PropertyType {
			get { return _propertyType; }
		}

		public override TypeConverter Converter {
			get { return _typeConverter; }
		}


	}
}
